package com.cw.lang.common.framework.inteceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import com.cw.base.common.model.constants.RestConstant;
import com.cw.base.common.model.util.AppParamUtil;
import com.cw.lang.common.exception.BizException;
import com.cw.lang.common.framework.converter.BaseRequestConverter;
import com.cw.lang.common.framework.converter.BaseUserRequestConverter;
import com.cw.lang.common.framework.enums.EnumRpcError;

/**
 * @author chenw
 * @version $$Id: LocalMvcHandlerInterceptor.java, v 0.1 2018/10/22 6:15 PM chenw Exp $$
 */
@Order(Ordered.HIGHEST_PRECEDENCE + 1000)
public class RequestHeaderMvcHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request.getRequestURI()
            .startsWith(RestConstant.BASE_URL_PREFIX)) {
            String baseRequest = request.getHeader(RestConstant.RPC_BASE_REQUEST);
            if (StringUtils.isBlank(baseRequest)) {
                throw new BizException(EnumRpcError.BASE_REQUEST_CAN_NOT_BE_NULL.getCode(),
                    EnumRpcError.BASE_REQUEST_CAN_NOT_BE_NULL.getDescription());
            }
            String baseUserRequest = request.getHeader(RestConstant.RPC_BASE_USER_REQUEST);
            AppParamUtil.setRequest(BaseRequestConverter.decode(baseRequest));
            AppParamUtil.setUserRequest(BaseUserRequestConverter.decode(baseUserRequest));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {
        AppParamUtil.removeRequest();
        AppParamUtil.removeUserRequest();
    }
}
